home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / cuj0593.zip / 1105054A < prev    next >
Text File  |  1993-03-16  |  2KB  |  100 lines

  1. // main.cc  -  Pond main program Listing 1
  2. #include <frog.h>
  3.  
  4. main()
  5.     {
  6.     PMF_VV pf = &Creature::move;  // bound to a virtual
  7.     Tadpole wiggly("Wiggly");
  8.     Bullfrog croaker("Croaker");
  9.     Pond walden;
  10.  
  11.     walden.insert(&wiggly);
  12.     walden.insert(&croaker);
  13.     walden.activate( pf ); // Tell all residents to move
  14.     return 0;
  15.     }
  16.  
  17.  ------------ output -----------------
  18. Wiggly Swimming jerkily
  19. Croaker - I'm jumping
  20.  
  21.  -----------------------------------
  22. //  Frog.h
  23. #ifndef FROG_H
  24. #define FROG_H
  25. #include <iostream.h>
  26. #include <rw/gslist.h>  // Rogue Wave tools.h++
  27.  
  28. class Creature
  29.     {
  30. public:
  31.     virtual void move() {} 
  32.     virtual ~Creature() {}
  33.     };
  34.  
  35. declare(GSlist,Creature)
  36.  
  37. class Frog : public Creature
  38.     {
  39. protected:
  40.     char *name;
  41. public:
  42.     Frog(char *p="Noname") { name = p; }
  43.     char *Name() { return name; }
  44.     virtual void move() {} 
  45.     virtual ~Frog() {}
  46.     };
  47.  
  48. class Tadpole : public Frog
  49.     {
  50. public:
  51.     Tadpole(char *name) : Frog(name) {};
  52.     void move(){cout << name << " Swimming jerkily\n";}
  53.     };
  54.  
  55. class Bullfrog : public Frog
  56.     {
  57. public:
  58.     Bullfrog(char *name) : Frog(name) {};
  59.     void move(){cout << name << " - I'm jumping\n"; }
  60.     };
  61.  
  62. class Pond
  63.     {
  64.     GSlist(Creature) list;  // singly linked creature list
  65. public:
  66.     // activate takes a ptr to any member func of Frog
  67.     // that takes a void arg and returns a void
  68.     // It turns out move() is the only one so far
  69.     // It iterates over all objects derived from 
  70.     // Creature base class in the Pond
  71.     void activate( void (Creature::*pf) () );
  72.     void insert(Creature *);
  73.     };
  74.  
  75. // this typedef must be after the class declarations
  76. // it may be useful to simplify declarations in the users program.
  77. // useful for pointing to move(void)
  78. typedef void (Creature::*PMF_VV)();   
  79. #endif
  80.  --------------------------------------------------------
  81. // Frog.cpp
  82. #include <stdlib.h>
  83. #include <frog.h>
  84.  
  85. void Pond::insert(Creature *f)
  86.     {
  87.     list.insert(f);
  88.     }
  89.  
  90. void Pond::activate( PMF_VV pmf_vv )
  91.     {
  92.     GSlistIterator(Creature) it(list);
  93.     Creature *resident;
  94.     while ( resident = (Creature *)it() ) 
  95.     {
  96.     (resident->*pmf_vv)();
  97.     }
  98.     }
  99.  
  100.